import browserPool from "../spider/browserPool.js";

const URL_GUPIAO = "https://gushitong.baidu.com/stock/ab-";
const PRICE_SELETOR = ".b_price";
const NAME_SELETOR = ".title_text";
const RETRY_TiME = 4;
export const getPriceAndName = async (gupiao_id, retryTime = 0) => {
  if(retryTime > RETRY_TiME) {
    return {
      result: false
    };
  }
  let browser = await browserPool.getBrowser();
  let page = await browserPool.getBrowserPageWithoutPicAndVideo(browser);
  try {
    let url = URL_GUPIAO + gupiao_id;
    await page.goto(url, {waitUntil: 'networkidle0'});
    await page.waitForSelector(PRICE_SELETOR);
    const price = await page.$eval(PRICE_SELETOR, (item) => {
      return item.innerHTML.replaceAll(' ', '').replaceAll('\n', '');
    });
    await page.waitForSelector(NAME_SELETOR);
    const name = await page.$eval(NAME_SELETOR, (item) => {
      return item.innerHTML.replaceAll(' ', '').replaceAll('\n', '');
    });
    await browserPool.backBrowser(browser);
    return {
      price: Number(price),
      name
    };
  } catch (e) {
    // 出现错误 重试
    await browserPool.browserUpdate(browser);
    return await getPriceAndName(gupiao_id, retryTime + 1);
  }
};
